package com.ruoyi.web.controller.common;

/**
 * @Auther: lihongming
 * @Date: 2023-07-27 14:07
 * @Description: com.ruoyi.web.controller.common
 * @Version: 1.0
 */

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.dto.FileChunkDTO;
import com.ruoyi.web.dto.FileChunkResultDTO;
import com.ruoyi.web.service.IUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploaderController {

    @Autowired
    private IUploadService uploadService;

    /**
     * 检查分片是否存在
     *
     * @return
     */
    @GetMapping("chunk")
    public AjaxResult checkChunkExist(FileChunkDTO chunkDTO) {
        FileChunkResultDTO fileChunkCheckDTO;
        try {
            fileChunkCheckDTO = uploadService.checkChunkExist(chunkDTO);
            return AjaxResult.success(fileChunkCheckDTO);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 上传文件分片
     *
     * @param chunkDTO
     * @return
     */
    @PostMapping("chunk")
    public AjaxResult uploadChunk(FileChunkDTO chunkDTO) {
        try {
            uploadService.uploadChunk(chunkDTO);
            return AjaxResult.success(chunkDTO.getIdentifier());
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 请求合并文件分片
     *
     * @param chunkDTO
     * @return
     */
    @PostMapping("merge")
    public AjaxResult mergeChunks(@RequestBody FileChunkDTO chunkDTO) {
        log.info("#########视频合并开始：{}",chunkDTO.toString());
        try {
            AjaxResult ajaxResult = uploadService.mergeChunk(chunkDTO.getIdentifier(), chunkDTO.getFilename(), chunkDTO.getTotalChunks());
            log.info("#########视频合并成功：{}",chunkDTO.toString());
            return ajaxResult;
        } catch (Exception e) {
            log.info("#########视频合并失败：{}",chunkDTO.toString());
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除redis key
     * 记录分片数据的redis
     *
     * @param identifier
     * @return
     */
    @GetMapping("delRedisKey/{identifier}")
    public AjaxResult delRedisKey(@PathVariable String identifier) {
        log.info("开始删除分片redis key：{}", identifier);
        uploadService.delRedisKey(identifier);
        log.info("完成删除分片redis key：{}", identifier);
        return AjaxResult.success();
    }
}
